<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="jquery.js"></script>
    <style>
        .red {
            border: 1px red solid;
            height: 300px;
            width: 400px;
        }

        .blue {
            border: 1px blue solid;
            height: 300px;
            width: 400px;
        }
    </style>
</head>

<body>
<video id="video" autoplay playsinline class="red"></video>
<canvas id="canvas" width="400" height="300"></canvas>
<button onclick="picture()">拍照</button>
<button onclick="download()">下载图片</button>


</body>
<script type="text/javascript">
    let stream = null;

    /**
     * 开始摄像头
     */
    (async function () {
        let constraints = {
            video: true,
            audio: false
        };
        // 声音太响，还是改成false
        stream = await navigator.mediaDevices.getUserMedia(constraints);
        document.getElementById("video").srcObject = stream;
    })();

    /**
     * 下载图片
     */
    function download() {

        let myCanvas=document.getElementById("canvas");
        // 创建一个 a 标签，并设置 href 和 download 属性
        const el = document.createElement('a');
        // 设置 href 为图片经过 base64 编码后的字符串，默认为 png 格式
        el.href = myCanvas.toDataURL("img/png");
        el.download = '拍照图片';
        // 创建一个点击事件并对 a 标签进行触发
        const event = new MouseEvent('click');
        el.dispatchEvent(event);
    }

    /**
     * 拍照
     */
    function picture() {
        // 流
        // x--从 x坐标轴开始获取
        // y--从 y 坐标轴开始获取
        // size-width
        // size-height
        document.getElementById("canvas").getContext("2d").drawImage(document.getElementById("video"), 0, 0, 400, 300)
    }




</script>

</html>